package com.clay.appointment.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.clay.appointment.common.page.PageInfo;
import com.clay.appointment.entity.hospital.Department;
import com.clay.appointment.repository.DepartmentRepository;
import com.clay.appointment.service.DepartmentService;
import com.clay.appointment.vo.hospital.DepartmentQueryVo;
import com.clay.appointment.vo.hospital.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author : clay
 * @Description:
 * @Date: Create in 10:47 2021/8/6
 * @Modified By:
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DepartmentRepository departmentRepository;


    @Override
    @Transactional
    public void save(Map<String, Object> paramMap) {
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);
        Query query = new Query(Criteria.where("hospitalCode").is(department.getHospitalCode()).and("departmentCode").is(department.getDepartmentCode()));

        List<Department> departments = mongoTemplate.find(query, Department.class, "Department");
        Department departmentExist = null;
        if (!departments.isEmpty()) {
            departmentExist = departments.get(0);
        }
        if (departmentExist != null) {
            Query query1 = new Query(Criteria.where("_id").is(departmentExist.getId()));
            Update update = new Update();
            department.setId(departmentExist.getId());
            department.setUpdateTime(new Date());
            if (department.getHospitalCode() != null) {
                update.set("hospitalCode", department.getHospitalCode());
            }
            if (department.getDepartmentCode() != null) {
                update.set("departmentCode", department.getDepartmentCode());
            }
            if (department.getDepartmentName() != null) {
                update.set("departmentName", department.getDepartmentName());
            }
            if (department.getIntro() != null) {
                update.set("intro", department.getIntro());
            }
            if (department.getBigcode() != null) {
                update.set("bigcode", department.getBigcode());
            }
            if (department.getBigname() != null) {
                update.set("bigname", department.getBigname());
            }
            update.set("updateTime", department.getUpdateTime());
            update.set("deleted", department.getDeleted());
            mongoTemplate.upsert(query1, update, department.getClass());
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setDeleted(false);
            mongoTemplate.save(department);
        }
    }

    @Override
    public PageInfo<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        //创建Pageable对象，设置当前页和每页记录数
        Pageable pageable = PageRequest.of(page - 1, limit);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setDeleted(false);
        //创建Example对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);
        Page<Department> all = departmentRepository.findAll(example, pageable);
        return PageInfo.buildPage(all, Department.class);
    }

    @Override
    public void removeDepartment(String hospitalCode, String departmentCode) {
        //根据医院编号和科室编号查询信息
        Department department = departmentRepository.getDepartmentByHospitalCodeAndDepartmentCode(hospitalCode, departmentCode);
        if (department != null) {
            //调用方法删除
            departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> findDepartmentTree(String hospitalCode) {
        ArrayList<DepartmentVo> result = new ArrayList<>();
        //根据医院编号查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHospitalCode(hospitalCode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> list = departmentRepository.findAll(example);
        //根据大科室编号分组
        Map<String, List<Department>> departmentMap = list.stream().collect(Collectors.groupingBy(Department::getBigcode));

        Set<Map.Entry<String, List<Department>>> entries = departmentMap.entrySet();
        for (Map.Entry<String, List<Department>> entry : entries) {
            //大科室编号
            String bigCode = entry.getKey();

            //获取这个分组下的科室列表
            List<Department> departmentList1 = entry.getValue();

            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepartmentCode(bigCode);
            departmentVo1.setDepartmentName(departmentList1.get(0).getBigname());

            //封装小科室
            ArrayList<DepartmentVo> children = new ArrayList<>();
            for (Department department : departmentList1) {
                DepartmentVo departmentVo2 = new DepartmentVo();
                departmentVo2.setDepartmentCode(department.getDepartmentCode());
                departmentVo2.setDepartmentName(department.getDepartmentName());
                children.add(departmentVo2);
            }
            departmentVo1.setChildren(children);
            result.add(departmentVo1);

        }

        return result;
    }

    @Override
    public String getDepartmentNameByDepartmentCodeAndHospitalCode(String departmentCode,String hospitalCode) {
        Department department= departmentRepository.getDepartmentByHospitalCodeAndDepartmentCode(hospitalCode,departmentCode);
        if(department!=null)
        {
            return department.getDepartmentName();
        }
        return null;
    }
}
